/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.rw;

import javax.jws.Oneway;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁：
 * 对于读的操作可以允许多个线程进行操作；（共享锁）
 * 对于写的操作，这能允许一个线程操作（独占锁）
 */
public class ReadWriteLock {

    public static void main(String[] args) {
        MycacheLock mycacheLock = new MycacheLock();

        //读
        for (int i = 1; i <= 5; i++) {
            final int tem = i;
            new Thread(()->{
                mycacheLock.get(String.valueOf(tem));
            },String.valueOf(i)).start();
        }

        //写
        for (int i = 1; i <= 5; i++) {
            final int tem = i;
            new Thread(()->{
                mycacheLock.set(String.valueOf(tem),tem);
            },String.valueOf(i)).start();
        }
    }


}


class MycacheLock {

    private volatile Map<String, Object> map = new HashMap<>();

    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //写的操作
    public void set(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入OK");
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    //读的操作
    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取OK");
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
